#!/bin/bash
SCRIPT_BASE_DIR=$( dirname "${BASH_SOURCE[0]}" )
source "${SCRIPT_BASE_DIR}/common/ip_utils.sh"

set -e

function bring_dev_up() {
    local n="$1"
    local dest="$2"
    local tap="$3"
    # 以下命令从poky/scripts/runqemu-ifup脚本得到
    sudo ip addr add 192.168.7.${n}/32 broadcast 192.168.7.255 dev ${tap}
    sudo ip link set dev ${tap} up # 该条命令不能放在最后
    sudo ip route add to 192.168.7.${dest} dev ${tap}
    sudo iptables -A  POSTROUTING -t nat -j MASQUERADE -s 192.168.7.${n}/32
    sudo iptables -A  POSTROUTING -t nat -j MASQUERADE -s 192.168.7.${dest}/32
}

function set_up_net() {
    local tapDev=$1
    read -p "To create virtual card ${tapDev}?(Y/N)" -n 1 answer
    echo 
    
    if [ "Y" != "${answer^}" ]
    then
        exit
    fi
    
    sudo tunctl -u $(whoami) -t "${tapDev}"
    bring_dev_up 1 2 ${tapDev}

    # 以下命令从poky/scripts/runqemu-ifup脚本得到
    sudo bash -c "echo 1 > /proc/sys/net/ipv4/ip_forward"
    sudo bash -c "echo 1 > /proc/sys/net/ipv4/conf/${tapDev}/proxy_arp"
    sudo iptables  -P FORWARD ACCEPT
}

function clean_net() {
    local tapDev=$1
    read -p "To delete virtual card ${tapDev}?(Y/N)" -n 1 answer
    echo 
    
    if [ "Y" != "${answer^}" ]
    then
        exit
    fi

    sudo ip link delete "${tapDev}"
}

function usage() {
    echo "Usage: $( basename "$0" ) [-d | -h]"
    echo "    设置运行AP demo单示例的虚拟网卡及网桥"
    echo "    设置的网卡名称为tap0"
    echo "    -d: 删除tap0虚拟设备"
    echo "    -h: 输出本信息"
    exit 1
}
 
while getopts ":dh" arg
do
    case "${arg}" in
        d)
            clean_net tap0
            exit 0
            ;;
        d|*)
            usage;;
    esac
done

link_dev_none_or_die tap0

set_up_net tap0
